package com.edais.service.imp;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.edais.dao.CouponsLuckDrawDao;
import com.edais.dao.LoanDao;
import com.edais.dao.RateRisesCouponsDao;
import com.edais.dao.UserDao;
import com.edais.domain.CouponsLuckDraw;
import com.edais.domain.LootShare;
import com.edais.domain.RateRisesCoupons;
import com.edais.domain.Scattered;
import com.edais.domain.User;
import com.edais.domain.UserSign;
import com.edais.service.RateRisesCouponsService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.DecimalFormatUtil;
import com.edais.util.random.RandomUtils;

@Service

@Transactional
public class RateRisesCouponsServiceImpl implements RateRisesCouponsService {

	private static final Log logger = LogFactory.getLog(RateRisesCouponsServiceImpl.class);
	
	private static final String signDateStrInit = "0000000000000000000000000000000";
	
	@Autowired
	private RateRisesCouponsDao rateRisesCouponsDao;
	
	@Autowired
	private UserDao usersDao;
	
	@Autowired 
	private CouponsLuckDrawDao couponsLuckDrawDao;
	
	@Autowired
	private LoanDao loanDao;
	
	@Autowired
	private RateRisesNewCouponsServiceImpl  raterisesNewCouponsServiceImpl;
	
	/**
	 * 根据参数查询我的加息券列表
	 * @throws Exception 
	 */
	@Override
	public Map<String, Object> queryRateRisesCouponsListByParams(
			Map<String, Object> paramsMap) throws Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		//如果存在用户 则填充mobile或userId
		if(paramsMap.get("userId")==null){
			User user = this.usersDao.getUserByParm(paramsMap);
			if(user!=null){
				paramsMap.put("userId", user.getId());
			}
		}
		if(paramsMap.get("mobile")==null || StringUtils.isBlank(paramsMap.get("mobile").toString()) ){
			String userId = paramsMap.get("userId").toString();
			User user = this.usersDao.getUserDetail(userId);
			if(user!=null){
				paramsMap.put("mobile", user.getMobile());
			}
		}
		
		String addKey = paramsMap.get("userId")!=null?paramsMap.get("userId").toString():paramsMap.get("mobile").toString() ;
		if(paramsMap.get("status")!=null){
			String status = paramsMap.get("status").toString();
			addKey = addKey+"_s"+status;
		}
		
		if(paramsMap.get("product")!=null){
			String product = paramsMap.get("product").toString();
			//优化
			addKey = addKey+"_p"+product;
		}
		
		
		
		//判断product类型
		if(paramsMap.get("product")!=null){
			if(StringUtils.isNotBlank(paramsMap.get("product").toString())){
				Integer product = Integer.parseInt(paramsMap.get("product").toString());
				switch(product){
				case 0:
					paramsMap.put("productId", "109");
					break;
				case 1:
					paramsMap.put("productId", "108");
					paramsMap.put("rateRisesDays", 1);
					break;
				case 3:
					paramsMap.put("productId", "108");
					paramsMap.put("rateRisesDays", 3);
					break;
				case 6:
					paramsMap.put("productId", "108");
					paramsMap.put("rateRisesDays", 6);
					break;
				case 12:
					paramsMap.put("productId", "108");
					paramsMap.put("rateRisesDays", 12);
					break;
				case 999:
					paramsMap.put("productId", "108");
					break;
				default : 
					paramsMap.put("remanDays", product);
				}
			}
		}
		int totalNum = this.rateRisesCouponsDao.queryRateRisesCouponsListByParamsCount(paramsMap);
		
		List<RateRisesCoupons> rateCouponsList = this.rateRisesCouponsDao.queryRateRisesCouponsListByParams(paramsMap);
		rtnMap.put("listSize", rateCouponsList.size());
		rtnMap.put("totalNum", totalNum);
		rtnMap.put("rateCouponsList", formatDateParams(rateCouponsList));
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功"); 
		
		
		
		return rtnMap;
	}
	
	@Override
	public Integer queryRateRisesCouponsListByParamsCount(
			Map<String, Object> paramsMap) throws Exception {
		// TODO Auto-generated method stub
		
		if(paramsMap.get("userId")==null){
			User user = this.usersDao.getUserByParm(paramsMap);
			if(user!=null){
				paramsMap.put("userId", user.getId());
			}
		}
		if(paramsMap.get("mobile")==null || StringUtils.isBlank(paramsMap.get("mobile").toString()) ){
			String userId = paramsMap.get("userId").toString();
			User user = this.usersDao.getUserDetail(userId);
			if(user!=null){
				paramsMap.put("mobile", user.getMobile());
			}
		}
		String addKey = paramsMap.get("userId")!=null?paramsMap.get("userId").toString():paramsMap.get("mobile").toString() ;
		if(paramsMap.get("status")!=null){
			String status = paramsMap.get("status").toString();
			addKey = addKey+"_s"+status;
		}
		
		if(paramsMap.get("product")!=null){
			String product = paramsMap.get("product").toString();
			//优化
			addKey = addKey+"_p"+product;
		}
		
		
		int totalNum = this.rateRisesCouponsDao.queryRateRisesCouponsListByParamsCount(paramsMap);
		
		return totalNum;
	}

	/**
	 * 根据获取途径查询每日获取的加息券
	 * @throws Exception 
	 */
	@Override
	public Map<String, Object> getTodayRateRisesCouponsByGetway(
			Map<String, Object> paramsMap) throws Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		//如果存在用户 则填充mobile或userId
		if(paramsMap.get("userId")==null){
			User user = this.usersDao.getUserByParm(paramsMap);
			if(user!=null){
				paramsMap.put("userId", user.getId());
			}
		}
		if(paramsMap.get("mobile")==null){
			String userId = paramsMap.get("userId").toString();
			User user = this.usersDao.getUserDetail(userId);
			if(user!=null){
				paramsMap.put("mobile", user.getMobile());
			}
		}
		
		String addKey = paramsMap.get("userId")!=null?paramsMap.get("userId").toString():paramsMap.get("mobile").toString();
		
		int totalNum = this.rateRisesCouponsDao.getTodayRateRisesCouponsByGetwayCount(paramsMap);
		List<RateRisesCoupons> rateCouponsList = this.rateRisesCouponsDao.getTodayRateRisesCouponsByGetway(paramsMap);
		rtnMap.put("totalNum", totalNum);
		rtnMap.put("listSize", rateCouponsList.size());
		rtnMap.put("rateCouponsList", formatDateParams(rateCouponsList));
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功");
		
		
		return rtnMap;
	}
	/**
	 * 获取加息券
	 * @throws Exception 
	 * @throws NumberFormatException 
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public Map<String, Object> addRateRisesCoupons(Map<String, Object> paramsMap) throws NumberFormatException, Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		String type = paramsMap.get("type").toString();
		String mobile = paramsMap.get("mobile")==null?null:paramsMap.get("mobile").toString();
		String userId = paramsMap.get("userId")==null?null:paramsMap.get("userId").toString();
		
		
		List<RateRisesCoupons> rateCouponsList = new ArrayList<RateRisesCoupons>();
		BigDecimal maxRateRises = new BigDecimal(findParamValueByName("sssq_max_rate_rises"));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyy-MM");
		Date currentDate = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTime(sdf.parse(sdf.format(currentDate)));
		Date validityPeriodDate = null;
		Integer shareSssqCouponsDays =  null;
		BigDecimal shareSssqCouponsRate = null;
		Integer validityPeriod = null;
		LootShare lootShare = null;
		Integer shareFixedCouponsMonth = null;
		BigDecimal shareFixedCouponsRate = null;
		String shareMobile = "";
		String mediaUid = "";
		String rtnStr = ""; 
		boolean existOrderId = false;
		Map<String, Object> map = null;
		String userSignFlag = findParamValueByName("user_sign_flag");
		String signDateStr = "";
		UserSign userSign = null;
		//判断类型
		paramsMap.put("currentDate", currentDate);
		switch(Integer.parseInt(type)){
		case 1:
			//注册获取加息券
			//定期3月期券
			RateRisesCoupons fixedCoupons1 = this.getBaseInfo(userId, mobile,currentDate);
			//定期6月期券
			RateRisesCoupons fixedCoupons2 = this.getBaseInfo(userId, mobile,currentDate);
			//活期券
			RateRisesCoupons sssqCoupons = this.getBaseInfo(userId, mobile,currentDate);
			
			//定期加息券参数信息
			Integer fixedRateRisesDays1 = Integer.parseInt(findParamValueByName("reg_fixed_coupons_number1"));
			Integer fixedRateRisesDays2 = Integer.parseInt(findParamValueByName("reg_fixed_coupons_number2"));
			BigDecimal fixedRateRises = new BigDecimal(findParamValueByName("reg_fixed_coupons_rate"));
			//活期加息券参数信息
			Integer sssqRateRisesDay = Integer.parseInt(findParamValueByName("reg_sssq_coupons_number"));
			BigDecimal sssqRateRises = new BigDecimal(findParamValueByName("reg_sssq_coupons_rate"));
			
			//定期加息券参数拼接
			//计算到期日期
			validityPeriod = Integer.parseInt(findParamValueByName("fixed_coupons_validity_period"));
			
			cal.add(Calendar.DATE, validityPeriod-1);
			validityPeriodDate = cal.getTime();
			
			//到期日期
			fixedCoupons1.setValidity_period(validityPeriodDate);
			fixedCoupons2.setValidity_period(validityPeriodDate);
			sssqCoupons.setValidity_period(validityPeriodDate);
			//产品id
			fixedCoupons1.setProduct_id("108");
			fixedCoupons2.setProduct_id("108");
			sssqCoupons.setProduct_id("109");
			//加息利率
			fixedCoupons1.setRate_rises(fixedRateRises);
			fixedCoupons2.setRate_rises(fixedRateRises);
			sssqCoupons.setRate_rises(sssqRateRises);
			//加息天数
			fixedCoupons1.setRate_rises_days(fixedRateRisesDays1);
			fixedCoupons2.setRate_rises_days(fixedRateRisesDays2);
			sssqCoupons.setRate_rises_days(sssqRateRisesDay);
			
			//短期标加息天数 根据参数控制，0－表示不启用，1－表示启用短期标送加息券
			String fhjxq_control=findParamValueByName("fhjxq_control");
			if(fhjxq_control==null||"".equals(fhjxq_control.trim())){
				fhjxq_control="0";
			}
			if("1".equals(fhjxq_control)){
				fixedCoupons1.setRemanDays(fixedRateRisesDays1);
				fixedCoupons2.setRemanDays(fixedRateRisesDays2);
				sssqCoupons.setRemanDays(0);
			}else{
				fixedCoupons1.setRemanDays(0);
				fixedCoupons2.setRemanDays(0);
				sssqCoupons.setRemanDays(0);
			}
			//获取途径
			fixedCoupons1.setGet_way("1");
			fixedCoupons2.setGet_way("1");
			sssqCoupons.setGet_way("1");
			//生成加息券
			this.rateRisesCouponsDao.insertRateRisesCoupons(fixedCoupons1);
			this.rateRisesCouponsDao.insertRateRisesCoupons(fixedCoupons2);
			this.rateRisesCouponsDao.insertRateRisesCoupons(sssqCoupons);
			//查询加息券返回列表
			
			rateCouponsList.add(sssqCoupons);
			rateCouponsList.add(fixedCoupons1);
			rateCouponsList.add(fixedCoupons2);
			break;
		case 2:
			
			shareMobile = mobile;
			paramsMap.put("shareMobile", shareMobile);
			
			lootShare = this.rateRisesCouponsDao.selectShareInfoByParams(paramsMap);
			
			if(lootShare==null){
				//判断需要增加活期加息券还是定期加息券
				String productId = paramsMap.get("productId").toString();
				if(productId.equals("109")){
					//每日分享领取加息券
					RateRisesCoupons shareCoupons =  this.getBaseInfo(userId, mobile,currentDate);
					//活期加息券的参数
					shareSssqCouponsDays = Integer.parseInt(findParamValueByName("share_sssq_coupons_number"));
					shareSssqCouponsRate = new BigDecimal(findParamValueByName("share_sssq_coupons_rate"));
					
					
					//分享参数拼接
					//计算到期日期
					validityPeriod = Integer.parseInt(findParamValueByName("sssq_coupons_validity_period"));
					cal.add(Calendar.DATE, validityPeriod-1);
					validityPeriodDate = cal.getTime();
					//到期日期
					shareCoupons.setValidity_period(validityPeriodDate);
					//产品ID
					shareCoupons.setProduct_id("109");
					//加息利率
					shareCoupons.setRate_rises(shareSssqCouponsRate);
					//加息天数
					shareCoupons.setRate_rises_days(shareSssqCouponsDays);
					//获取途径
					shareCoupons.setGet_way("2");
					//拼接查询参数
					Map<String,Object> shareReqMap = new HashMap<String,Object>();
					shareReqMap.put("userId", userId);
					shareReqMap.put("mobile", mobile);
					if(existOrderId){
						shareReqMap.put("useFlag", "2");
					}
					
					this.rateRisesCouponsDao.insertRateRisesCoupons(shareCoupons);
					
					rateCouponsList.add(shareCoupons);
					useRateRisesCouponsPassive(shareCoupons.getUser_id(), shareCoupons.getMobile(), rateCouponsList, "2");
					
					BigDecimal shareRateRises = this.rateRisesCouponsDao.selectTodayShareGetCouponsRateRises(shareReqMap);
					
					if(shareRateRises.compareTo(maxRateRises)>0){
						rtnMap.put("rescode", Consts.ERROR_CODE);
						rtnMap.put("resmsg", "");
						rtnMap.put("resmsg_cn", "对不起，当日分享获取加息券已满10次！");
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return rtnMap;
					}
					
				}else if(productId.equals("108")){
					//每日分享领取加息券
					RateRisesCoupons shareCoupons =  this.getBaseInfo(userId, mobile,currentDate);
					//定期加息券参数
					shareFixedCouponsMonth = Integer.parseInt(findParamValueByName("share_fixed_coupons_number"));
					shareFixedCouponsRate = new BigDecimal(findParamValueByName("share_fixed_coupons_rate"));
					
					//计算到期日期
					validityPeriod = Integer.parseInt(findParamValueByName("fixed_coupons_validity_period"));
					cal.add(Calendar.DATE, validityPeriod-1);
					validityPeriodDate = cal.getTime();
					
					//到期日期
					shareCoupons.setValidity_period(validityPeriodDate);
					//产品ID
					shareCoupons.setProduct_id("108");
					//加息利率
					shareCoupons.setRate_rises(shareFixedCouponsRate);
					//加息天数
					shareCoupons.setRate_rises_days(shareFixedCouponsMonth);
					//获取途径
					shareCoupons.setGet_way("2");
					
					this.rateRisesCouponsDao.insertRateRisesCoupons(shareCoupons);
					
					rateCouponsList.add(shareCoupons);
				}
				
				lootShare = new LootShare();
				lootShare.setLoot_mobile(null);
				lootShare.setShare_mobile(paramsMap.get("shareMobile").toString());
				lootShare.setLoot_date(sdf.parse(sdf.format(new Date())));
				
				this.rateRisesCouponsDao.insertLootShare(lootShare);
			}else{
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("resmsg_cn", "对不起，今天已经分享过该信息！");
				return rtnMap;
			}
			
			break;
		case 3:
			map = new HashMap<String,Object>();
			shareMobile = paramsMap.get("shareMobile")==null?null:paramsMap.get("shareMobile").toString();
			if(shareMobile!=null){
				map.put("mobile", shareMobile);
				User user = this.usersDao.getUserByParm(map);
				if(user!=null){
					Long userLongId = Long.parseLong(user.getId().toString());
					if(userLongId!=null){
						String transCode = "E310064";
						Map<String, Object> queryCoreMap = new HashMap<String, Object>();
						queryCoreMap.put("userId", userLongId);
						queryCoreMap.put("planId", "109");
						String jsonStr = CommonUtil.constructJsonStr(transCode,
								null, queryCoreMap);
						rtnStr = CommonUtil.getCoreValue(jsonStr);
						JSONObject jsonObject = JSONObject.fromObject(rtnStr);
						existOrderId = Boolean.parseBoolean(jsonObject.getString("existOrderId"));
					}
					
				}
			}
			//判断是否是同一个微信标识进行获取加息券
			lootShare = this.rateRisesCouponsDao.queryLootShareInfoByWeixinOpenId(paramsMap);
			mediaUid = paramsMap.get("mediaUid").toString();
			if(lootShare!=null){
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("resmsg_cn", "对不起，该微信号已经抢过该分享的加息券！");
				return rtnMap;
			}
			//判断是否已经抢过
			lootShare = this.rateRisesCouponsDao.selectLootShareInfoByParams(paramsMap);
			shareMobile = paramsMap.get("shareMobile").toString();
			
			if(lootShare==null){
				//被他人查看分享领取加息券
				RateRisesCoupons beViewCoupons =  this.getBaseInfo(userId, shareMobile,currentDate);
				//活期加息券的参数
				shareSssqCouponsDays = Integer.parseInt(findParamValueByName("share_sssq_coupons_number"));
				shareSssqCouponsRate = new BigDecimal(findParamValueByName("share_sssq_coupons_rate"));
				//分享参数拼接
				validityPeriod = Integer.parseInt(findParamValueByName("sssq_coupons_validity_period"));
				cal.add(Calendar.DATE, validityPeriod-1);
				validityPeriodDate = cal.getTime();
				//到期日期
				beViewCoupons.setValidity_period(validityPeriodDate);
				//产品ID
				beViewCoupons.setProduct_id("109");
				//加息利率
				beViewCoupons.setRate_rises(shareSssqCouponsRate);
				//加息天数
				beViewCoupons.setRate_rises_days(shareSssqCouponsDays);
				//加息途径 
				beViewCoupons.setGet_way("3");
				
				//拼接查询参数
				Map<String,Object> shareReqMap = new HashMap<String,Object>();
				shareReqMap.put("userId", userId);
				shareReqMap.put("mobile", shareMobile);
				if(existOrderId){
					shareReqMap.put("useFlag", "2");
				}
				//Integer shareCount = this.rateRisesCouponsDao.selectTodayShareGetCouponsCount(shareReqMap);
				this.rateRisesCouponsDao.insertRateRisesCoupons(beViewCoupons);
				
				rateCouponsList.add(beViewCoupons);
				useRateRisesCouponsPassive(beViewCoupons.getUser_id(), beViewCoupons.getMobile(), rateCouponsList, "2");
				
				BigDecimal shareRateRises = this.rateRisesCouponsDao.selectTodayShareGetCouponsRateRises(shareReqMap);
				if(shareRateRises.compareTo(maxRateRises)>0){
					rtnMap.put("rescode", Consts.ERROR_CODE);
					rtnMap.put("resmsg", "");
					rtnMap.put("resmsg_cn", "对不起，当日分享获取加息券已满10次！");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return rtnMap;
				}
				
			}else{
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("resmsg_cn", "对不起，已经被该用户查看过当日分享！");
				return rtnMap;
			}
			
			break;
		case 4:
			map = new HashMap<String,Object>();
			shareMobile = paramsMap.get("shareMobile")==null?null:paramsMap.get("shareMobile").toString();
			if(shareMobile!=null){
				map.put("mobile", mobile);
				User user = this.usersDao.getUserByParm(map);
				if(user!=null){
					Long userLongId = Long.parseLong(user.getId().toString());
					if(userLongId!=null){
						String transCode = "E310064";
						Map<String, Object> queryCoreMap = new HashMap<String, Object>();
						queryCoreMap.put("userId", userLongId);
						queryCoreMap.put("planId", "109");
						String jsonStr = CommonUtil.constructJsonStr(transCode,
								null, queryCoreMap);
						rtnStr = CommonUtil.getCoreValue(jsonStr);
						JSONObject jsonObject = JSONObject.fromObject(rtnStr);
						existOrderId = Boolean.parseBoolean(jsonObject.getString("existOrderId"));
					}
					
				}
			}
			Map<String,Object> shareReqMap = new HashMap<String,Object>();
			shareReqMap.put("userId", userId);
			shareReqMap.put("mobile", mobile);
			if(existOrderId){
				shareReqMap.put("useFlag", "2");
			}
			BigDecimal shareRateRises = this.rateRisesCouponsDao.selectTodayShareGetCouponsRateRises(shareReqMap);
			//判断是否是同一个微信标识进行获取加息券
			lootShare = this.rateRisesCouponsDao.queryLootShareInfoByWeixinOpenId(paramsMap);
			mediaUid = paramsMap.get("mediaUid").toString();
			if(lootShare!=null){
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
				if(shareRateRises.compareTo(maxRateRises)>=0){
					rtnMap.put("lootFlag", "2");
					rtnMap.put("resmsg_cn", "对不起，当日分享获取加息券已满10次！");
				}else{
					rtnMap.put("lootFlag", "1");
					rtnMap.put("resmsg_cn", "对不起，该微信号已经抢过该分享的加息券！");
				}
				
				return rtnMap;
			}
			
			//判断是否已经抢过
			lootShare = this.rateRisesCouponsDao.selectLootShareInfoByParams(paramsMap);
			
			if(lootShare==null){
				//查看分享领取加息券
				RateRisesCoupons viewCoupons =  this.getBaseInfo(userId, mobile,currentDate);
				//活期加息券的参数
				shareSssqCouponsDays = Integer.parseInt(findParamValueByName("share_sssq_coupons_number"));
				shareSssqCouponsRate = new BigDecimal(findParamValueByName("share_sssq_coupons_rate"));
				//分享参数拼接
				validityPeriod = Integer.parseInt(findParamValueByName("sssq_coupons_validity_period"));
				cal.add(Calendar.DATE, validityPeriod-1);
				validityPeriodDate = cal.getTime();
				//到期日期
				viewCoupons.setValidity_period(validityPeriodDate);
				//产品ID
				viewCoupons.setProduct_id("109");
				//加息利率
				viewCoupons.setRate_rises(shareSssqCouponsRate);
				//加息天数
				viewCoupons.setRate_rises_days(shareSssqCouponsDays);
				//加息途径 
				viewCoupons.setGet_way("4");
				
				//拼接查询参数
				
				//保存分享信息
				lootShare = new LootShare();
				lootShare.setLoot_mobile(paramsMap.get("mobile").toString());
				lootShare.setShare_mobile(paramsMap.get("shareMobile").toString());
				lootShare.setLoot_date(sdf.parse(sdf.format(new Date())));
				lootShare.setLoot_weixin_openid(mediaUid);
				//当前事务不回滚
				raterisesNewCouponsServiceImpl.insertLootShare(lootShare);
				//Integer shareCount = this.rateRisesCouponsDao.selectTodayShareGetCouponsCount(shareReqMap);
				
				this.rateRisesCouponsDao.insertRateRisesCoupons(viewCoupons);
				
				rateCouponsList.add(viewCoupons);
				
				useRateRisesCouponsPassive(viewCoupons.getUser_id(), viewCoupons.getMobile(), rateCouponsList, "2");
				
			}else{
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("resmsg_cn", "对不起，该手机号已经抢过该分享的加息券！");
				return rtnMap;
			}
			if(shareRateRises.compareTo(maxRateRises)>=0){
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("lootFlag", "2");
				rtnMap.put("resmsg_cn", "对不起，当日分享获取加息券已满10次！");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return rtnMap;
			}
			break;
		case 5:
			//活期收益自动产生随机加息券
			RateRisesCoupons autoCoupons = this.getBaseInfo(userId, mobile,currentDate);
			//收益加息券的参数
			shareSssqCouponsDays = Integer.parseInt(findParamValueByName("share_sssq_coupons_number"));
			
			//分享参数拼接
			validityPeriod = Integer.parseInt(findParamValueByName("income_sssq_coupons_number"));
			cal.add(Calendar.DATE, validityPeriod-1);
			validityPeriodDate = cal.getTime();
			//到期日期
			autoCoupons.setValidity_period(validityPeriodDate);
			//产品ID
			autoCoupons.setProduct_id("109");
			//随机产生加息券的加息利率
			BigDecimal randomRate = RandomUtils.randomLuckDraw();
			autoCoupons.setRate_rises(randomRate);
			//加息的天数 1天
			autoCoupons.setRate_rises_days(shareSssqCouponsDays);
			//加息途径 
			autoCoupons.setGet_way("5");
			
			this.rateRisesCouponsDao.insertRateRisesCoupons(autoCoupons);
			
			rateCouponsList.add(autoCoupons);
			break;
		case 8:
			//注册获取加息券
			//定期3月期券
			RateRisesCoupons kfixedCoupons1 = this.getBaseInfo(userId, mobile,currentDate);
			//定期6月期券
			RateRisesCoupons kfixedCoupons2 = this.getBaseInfo(userId, mobile,currentDate);
			//活期券
			RateRisesCoupons ksssqCoupons = this.getBaseInfo(userId, mobile,currentDate);
			
			//定期加息券参数信息
			Integer kfixedRateRisesDays1 = Integer.parseInt(findParamValueByName("k_reg_fixed_coupons_number1"));
			Integer kfixedRateRisesDays2 = Integer.parseInt(findParamValueByName("k_reg_fixed_coupons_number2"));
			BigDecimal kfixedRateRises = new BigDecimal(findParamValueByName("k_reg_fixed_coupons_rate"));
			//活期加息券参数信息
			Integer ksssqRateRisesDay = Integer.parseInt(findParamValueByName("k_reg_sssq_coupons_number"));
			BigDecimal ksssqRateRises = new BigDecimal(findParamValueByName("k_reg_sssq_coupons_rate"));
			
			//定期加息券参数拼接
			//计算到期日期
			validityPeriod = Integer.parseInt(findParamValueByName("k_fixed_coupons_validity_period"));
			
			cal.add(Calendar.DATE, validityPeriod-1);
			validityPeriodDate = cal.getTime();
			
			//到期日期
			kfixedCoupons1.setValidity_period(validityPeriodDate);
			kfixedCoupons2.setValidity_period(validityPeriodDate);
			ksssqCoupons.setValidity_period(validityPeriodDate);
			//产品id
			kfixedCoupons1.setProduct_id("108");
			kfixedCoupons2.setProduct_id("108");
			ksssqCoupons.setProduct_id("109");
			//加息利率
			kfixedCoupons1.setRate_rises(kfixedRateRises);
			kfixedCoupons2.setRate_rises(kfixedRateRises);
			ksssqCoupons.setRate_rises(ksssqRateRises);
			//加息天数
			kfixedCoupons1.setRate_rises_days(kfixedRateRisesDays1);
			kfixedCoupons2.setRate_rises_days(kfixedRateRisesDays2);
			ksssqCoupons.setRate_rises_days(ksssqRateRisesDay);
			//获取途径
			kfixedCoupons1.setGet_way(type);
			kfixedCoupons2.setGet_way(type);
			ksssqCoupons.setGet_way(type);                            
			//生成加息券
			this.rateRisesCouponsDao.insertRateRisesCoupons(kfixedCoupons1);
			this.rateRisesCouponsDao.insertRateRisesCoupons(kfixedCoupons2);
			this.rateRisesCouponsDao.insertRateRisesCoupons(ksssqCoupons);
			//查询加息券返回列表
			
			rateCouponsList.add(ksssqCoupons);
			rateCouponsList.add(kfixedCoupons1);
			rateCouponsList.add(kfixedCoupons1);
			break;
		case 9:
			//判断签到开关是否开启
			if(StringUtils.isNotBlank(userSignFlag)){
				if(userSignFlag.equals("N")){
					rtnMap.put("rescode", Consts.ERROR_CODE);
					rtnMap.put("resmsg", "");
					rtnMap.put("resmsg_cn", "签到功能还未开放，敬请期待！");
					return rtnMap;
				}
			}else{
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("resmsg_cn", "签到功能还未开放，敬请期待！");
				return rtnMap;
			}
			/*
			 * 微信签到 
			 */
			BigDecimal signWechatRate =  new BigDecimal(findParamValueByName("sign_wechat_rate"));
			
			//判断用户当月是否存在签到信息
			userSign = this.rateRisesCouponsDao.queryUserCurrentMonthSign(paramsMap);
			
			try{
				
				if(userSign==null){
					//当月不存在信息时增加签到记录
					userSign = new UserSign();
					userSign.setUser_id(Long.parseLong(userId));
					//sign_flag为每天签到的标识
					userSign.setSign_flag("WX");
					signDateStr = getSignDateStr(signDateStrInit,'1',currentDate);
					userSign.setSign_month(sdfMonth.format(currentDate));
					userSign.setSign_date_str(signDateStr);
					userSign.setCreate_time(currentDate);
					userSign.setSign_time(sdf.parse(sdf.format(currentDate)));
					
					//插入一条签到记录
					
					rateRisesCouponsDao.addUserSignInfo(userSign);
				}else{
					signDateStr = getSignDateStr(userSign.getSign_date_str(),'1',currentDate);
					userSign.setSign_flag("WX");
					userSign.setSign_date_str(signDateStr);
					userSign.setUpdate_time(currentDate);
					userSign.setSign_time(sdf.parse(sdf.format(currentDate)));
				
					//更新记录信息
					int result=rateRisesCouponsDao.updateUserSignInfo(userSign); 
					if (result != 1) {
						//判断是否更新成功
						rtnMap.put("rescode", Consts.ERROR_CODE);
						rtnMap.put("resmsg", "");
						rtnMap.put("resmsg_cn", "今天已完成签到！");
						return rtnMap;
					}
					
				}
			}catch(Exception e){
				//出现并发问题（唯一约束会报错） 返回已经签到
				e.printStackTrace();
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("resmsg_cn", "今天已完成签到！");
				return rtnMap;
			}
			
			//生成加息券
			RateRisesCoupons wechatSignRate = this.getBaseInfo(userId, mobile,currentDate);
			//分享参数拼接
			validityPeriod = 1;
			cal.add(Calendar.DATE, validityPeriod-1);
			validityPeriodDate = cal.getTime();
			//到期日期
			wechatSignRate.setValidity_period(validityPeriodDate);
			//产品ID
			wechatSignRate.setProduct_id("109");
			//加息利率
			wechatSignRate.setRate_rises(signWechatRate);
			//加息天数
			wechatSignRate.setRate_rises_days(1);
			//加息途径 
			wechatSignRate.setGet_way("9");
			
			this.rateRisesCouponsDao.insertRateRisesCoupons(wechatSignRate);
			
			rateCouponsList.add(wechatSignRate);
			//使用加息券
			useRateRisesCouponsPassive(wechatSignRate.getUser_id(), wechatSignRate.getMobile(), rateCouponsList, "4");
			
			break;
		case 10:
			/*
			 * app签到 
			 */
			if(StringUtils.isNotBlank(userSignFlag)){
				if(userSignFlag.equals("N")){
					rtnMap.put("rescode", Consts.ERROR_CODE);
					rtnMap.put("resmsg", "");
					rtnMap.put("resmsg_cn", "签到功能还未开放，敬请期待！");
					return rtnMap;
				}
			}else{
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("resmsg_cn", "签到功能还未开放，敬请期待！");
				return rtnMap;
			}
			BigDecimal signAppRate =  new BigDecimal(findParamValueByName("sign_app_rate"));
			
			//判断用户当月是否存在签到信息
			userSign = this.rateRisesCouponsDao.queryUserCurrentMonthSign(paramsMap);
			
			
			try{
				
				if(userSign==null){
					//当月不存在信息时增加签到记录
					userSign = new UserSign();
					userSign.setUser_id(Long.parseLong(userId));
					//sign_flag为每天签到的标识
					userSign.setSign_flag("APP");
					signDateStr = getSignDateStr(signDateStrInit,'2',currentDate);
					userSign.setSign_month(sdfMonth.format(currentDate));
					userSign.setSign_date_str(signDateStr);
					userSign.setCreate_time(currentDate);
					userSign.setSign_time(sdf.parse(sdf.format(currentDate)));
					
					//插入一条签到记录
					
					rateRisesCouponsDao.addUserSignInfo(userSign);
				}else{
					signDateStr = getSignDateStr(userSign.getSign_date_str(),'2',currentDate);
					userSign.setSign_flag("APP");
					userSign.setSign_date_str(signDateStr);
					userSign.setUpdate_time(currentDate);
					userSign.setSign_time(sdf.parse(sdf.format(currentDate)));
				
					//更新记录信息
					int result=rateRisesCouponsDao.updateUserSignInfo(userSign); 
					if (result != 1) {
						//判断是否更新成功
						rtnMap.put("rescode", Consts.ERROR_CODE);
						rtnMap.put("resmsg", "");
						rtnMap.put("resmsg_cn", "今天已完成签到！");
						return rtnMap;
					}
					
				}
				
			}catch(Exception e){
				//出现并发问题（唯一约束会报错） 返回已经签到
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("resmsg_cn", "今天已完成签到！");
				return rtnMap;
			}
			//生成加息券
			RateRisesCoupons appSignRate = this.getBaseInfo(userId, mobile,currentDate);
			//分享参数拼接
			validityPeriod = 1;
			cal.add(Calendar.DATE, validityPeriod-1);
			validityPeriodDate = cal.getTime();
			//到期日期
			appSignRate.setValidity_period(validityPeriodDate);
			//产品ID
			appSignRate.setProduct_id("109");
			//加息利率
			appSignRate.setRate_rises(signAppRate);
			//加息天数
			appSignRate.setRate_rises_days(1);
			//加息途径 
			appSignRate.setGet_way("10");
			
			this.rateRisesCouponsDao.insertRateRisesCoupons(appSignRate);
			
			rateCouponsList.add(appSignRate);
			//使用加息券
			useRateRisesCouponsPassive(appSignRate.getUser_id(), appSignRate.getMobile(), rateCouponsList, "5");
			
			break;
			
		default :
			break;
		}
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "获取加息券成功");
		rtnMap.put("rateCouponsList", formatDateParams(rateCouponsList));
		rtnMap.put("rateCouponsCount", rateCouponsList.size());
		return rtnMap;
	}
	
	/**
	 * 分享加息券check
	 */
	@Override
	public Map<String, Object> checkShareRateRises(Map<String, Object> paramsMap)
			throws Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		String type = paramsMap.get("type").toString();
		String mobile = paramsMap.get("mobile")==null?null:paramsMap.get("mobile").toString();
		String userId = paramsMap.get("userId")==null?null:paramsMap.get("userId").toString();
		String shareMobile = paramsMap.get("shareMobile")==null?null:paramsMap.get("shareMobile").toString();
		String mediaUid = paramsMap.get("mediaUid").toString();
		boolean existOrderId = false;
		Map<String, Object> map = null;
		String rtnStr = "";
		LootShare lootShare = null;
		BigDecimal maxRateRises = new BigDecimal(findParamValueByName("sssq_max_rate_rises"));
		
		switch(Integer.parseInt(type)){
		case 3:
			map = new HashMap<String,Object>();
			if(shareMobile!=null){
				map.put("mobile", shareMobile);
				User user = this.usersDao.getUserByParm(map);
				if(user!=null){
					Long userLongId = Long.parseLong(user.getId().toString());
					if(userLongId!=null){
						String transCode = "E310064";
						Map<String, Object> queryCoreMap = new HashMap<String, Object>();
						queryCoreMap.put("userId", userLongId);
						queryCoreMap.put("planId", "109");
						String jsonStr = CommonUtil.constructJsonStr(transCode,
								null, queryCoreMap);
						rtnStr = CommonUtil.getCoreValue(jsonStr);
						JSONObject jsonObject = JSONObject.fromObject(rtnStr);
						existOrderId = Boolean.parseBoolean(jsonObject.getString("existOrderId"));
					}
					
				}
			}
			//判断是否是同一个微信标识进行获取加息券
			lootShare = this.rateRisesCouponsDao.queryLootShareInfoByWeixinOpenId(paramsMap);
			if(lootShare!=null){
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("resmsg_cn", "对不起，该微信号已经抢过该分享的加息券！");
				return rtnMap;
			}
			//判断是否已经抢过
			lootShare = this.rateRisesCouponsDao.selectLootShareInfoByParams(paramsMap);
			if(lootShare==null){
				//拼接查询参数
				Map<String,Object> shareReqMap = new HashMap<String,Object>();
				shareReqMap.put("userId", userId);
				shareReqMap.put("mobile", shareMobile);
				if(existOrderId){
					shareReqMap.put("useFlag", "2");
				}
				BigDecimal shareRateRises = this.rateRisesCouponsDao.selectTodayShareGetCouponsRateRises(shareReqMap);
				
				if(shareRateRises.compareTo(maxRateRises)>=0){
					rtnMap.put("rescode", Consts.ERROR_CODE);
					rtnMap.put("resmsg", "");
					rtnMap.put("resmsg_cn", "对不起，当日分享获取加息券已满10次！");
					return rtnMap;
				}
				
			}else{
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("resmsg_cn", "对不起，已经被该用户查看过当日分享！");
				return rtnMap;
			}
			break;
		case 4:
			map = new HashMap<String,Object>();
			if(shareMobile!=null){
				map.put("mobile", mobile);
				User user = this.usersDao.getUserByParm(map);
				if(user!=null){
					Long userLongId = Long.parseLong(user.getId().toString());
					if(userLongId!=null){
						String transCode = "E310064";
						Map<String, Object> queryCoreMap = new HashMap<String, Object>();
						queryCoreMap.put("userId", userLongId);
						queryCoreMap.put("planId", "109");
						String jsonStr = CommonUtil.constructJsonStr(transCode,
								null, queryCoreMap);
						rtnStr = CommonUtil.getCoreValue(jsonStr);
						JSONObject jsonObject = JSONObject.fromObject(rtnStr);
						existOrderId = Boolean.parseBoolean(jsonObject.getString("existOrderId"));
					}
					
				}
			}
			Map<String,Object> shareReqMap = new HashMap<String,Object>();
			shareReqMap.put("userId", userId);
			shareReqMap.put("mobile", mobile);
			if(existOrderId){
				shareReqMap.put("useFlag", "2");
			}
			BigDecimal shareRateRises = this.rateRisesCouponsDao.selectTodayShareGetCouponsRateRises(shareReqMap);
			//判断是否是同一个微信标识进行获取加息券
			lootShare = this.rateRisesCouponsDao.queryLootShareInfoByWeixinOpenId(paramsMap);
			if(lootShare!=null){
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
				if(shareRateRises.compareTo(maxRateRises)>=0){
					rtnMap.put("lootFlag", "2");
					rtnMap.put("resmsg_cn", "对不起，当日分享获取加息券已满10次！");
				}else{
					rtnMap.put("lootFlag", "1");
					rtnMap.put("resmsg_cn", "对不起，该微信号已经抢过该分享的加息券！");
				}
				
				return rtnMap;
			}
			
			//判断是否已经抢过
			lootShare = this.rateRisesCouponsDao.selectLootShareInfoByParams(paramsMap);

			if(lootShare==null){
				if(shareRateRises.compareTo(maxRateRises)>=0){
					rtnMap.put("rescode", Consts.ERROR_CODE);
					rtnMap.put("resmsg", "");
					rtnMap.put("lootFlag", "2");
					rtnMap.put("resmsg_cn", "对不起，当日分享获取加息券已满10次！");
					return rtnMap;
				}
			}else{
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("resmsg_cn", "对不起，该手机号已经抢过该分享的加息券！");
				return rtnMap;
			}
			break;
		}
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功，可获取加息券");
		return rtnMap;
	}
	/**
	 * K码激活送加息券
	 */
	@Override
	@Async
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public Map<String, Object> shareKNotifyAddCoupons(
			Map<String, Object> paramsMap) throws Exception {
		
		Date currentDate = new Date();
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		String type = paramsMap.get("type").toString();
		String mobile = paramsMap.get("mobile")==null?null:paramsMap.get("mobile").toString();
		String userId = paramsMap.get("userId")==null?null:paramsMap.get("userId").toString();
		
		List<RateRisesCoupons> rateCouponsList = new ArrayList<RateRisesCoupons>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(sdf.parse(sdf.format(new Date())));
		Date validityPeriodDate = null;
		Integer validityPeriod = null;
		
		//注册获取加息券
		//定期3月期券
		RateRisesCoupons fixedCoupons1 = this.getBaseInfo(userId, mobile,currentDate);
		//定期6月期券
		RateRisesCoupons fixedCoupons2 = this.getBaseInfo(userId, mobile,currentDate);
		//活期券
		RateRisesCoupons sssqCoupons = this.getBaseInfo(userId, mobile,currentDate);
		
		//定期加息券参数信息
		Integer fixedRateRisesDays1 = Integer.parseInt(findParamValueByName("k_reg_fixed_coupons_number1"));
		Integer fixedRateRisesDays2 = Integer.parseInt(findParamValueByName("k_reg_fixed_coupons_number2"));
		BigDecimal fixedRateRises = new BigDecimal(findParamValueByName("k_reg_fixed_coupons_rate"));
		//活期加息券参数信息
		Integer sssqRateRisesDay = Integer.parseInt(findParamValueByName("k_reg_sssq_coupons_number"));
		BigDecimal sssqRateRises = new BigDecimal(findParamValueByName("k_reg_sssq_coupons_rate"));
		
		//定期加息券参数拼接
		//计算到期日期
		validityPeriod = Integer.parseInt(findParamValueByName("k_fixed_coupons_validity_period"));
		
		cal.add(Calendar.DATE, validityPeriod-1);
		validityPeriodDate = cal.getTime();
		
		//到期日期
		fixedCoupons1.setValidity_period(validityPeriodDate);
		fixedCoupons2.setValidity_period(validityPeriodDate);
		sssqCoupons.setValidity_period(validityPeriodDate);
		//产品id
		fixedCoupons1.setProduct_id("108");
		fixedCoupons2.setProduct_id("108");
		sssqCoupons.setProduct_id("109");
		//加息利率
		fixedCoupons1.setRate_rises(fixedRateRises);
		fixedCoupons2.setRate_rises(fixedRateRises);
		sssqCoupons.setRate_rises(sssqRateRises);
		//加息天数
		fixedCoupons1.setRate_rises_days(fixedRateRisesDays1);
		fixedCoupons2.setRate_rises_days(fixedRateRisesDays2);
		sssqCoupons.setRate_rises_days(sssqRateRisesDay);
		
		//短期标加息天数 根据参数控制，0－表示不启用，1－表示启用短期标送加息券
		String fhjxq_control=findParamValueByName("fhjxq_control");
		if(fhjxq_control==null||"".equals(fhjxq_control.trim())){
			fhjxq_control="0";
		}
		if("1".equals(fhjxq_control)){
			fixedCoupons1.setRemanDays(fixedRateRisesDays1);
			fixedCoupons2.setRemanDays(fixedRateRisesDays2);
			sssqCoupons.setRemanDays(0);
		}else{
			fixedCoupons1.setRemanDays(0);
			fixedCoupons2.setRemanDays(0);
			sssqCoupons.setRemanDays(0);
		}
		//获取途径
		fixedCoupons1.setGet_way(type);
		fixedCoupons2.setGet_way(type);
		sssqCoupons.setGet_way(type);
		//生成加息券
		this.rateRisesCouponsDao.insertRateRisesCoupons(fixedCoupons1);
		this.rateRisesCouponsDao.insertRateRisesCoupons(fixedCoupons2);
		this.rateRisesCouponsDao.insertRateRisesCoupons(sssqCoupons);
		//查询加息券返回列表
		
		rateCouponsList.add(sssqCoupons);
		rateCouponsList.add(fixedCoupons1);
		rateCouponsList.add(fixedCoupons2);
		
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "获取加息券成功");
		rtnMap.put("rateCouponsList", formatDateParams(rateCouponsList));
		rtnMap.put("rateCouponsCount", rateCouponsList.size());
		return rtnMap;
	}
	
	/**
	 * 使用加息券
	 * @throws Exception 
	 */
	@Override
	public Map<String, Object> useRateRisesCoupons(Map<String, Object> paramsMap) throws Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		String orderId = paramsMap.get("orderId").toString();
		String productId = paramsMap.get("productId").toString();
		
		String rateIds = paramsMap.get("rateIds").toString();
		String [] rateIdsArray = rateIds.split(",");
		
		//获取订单信息
		//查询当天的加息券列表
		List<RateRisesCoupons> couponsList = this.rateRisesCouponsDao.getRateRisesListByRateIds(rateIdsArray);
		String transCode = "E320010";
		Map<String, Object> queryCoreMap = new HashMap<String, Object>();
		queryCoreMap.put("orderId", orderId);
		String jsonStr = CommonUtil.constructJsonStr(transCode,
				null, queryCoreMap);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		String orderProductType = jsonObject.getString("PRODUCT_TYPE");
		//产品ID检查
		boolean checkProductType = true; 
		boolean checkUseCoupons = true;
		BigDecimal allRateRises = BigDecimal.ZERO;
		for(RateRisesCoupons coupons : couponsList){
			if(!coupons.getProduct_id().equals(orderProductType)){
				checkProductType = false;
				break;
			}
			if(coupons.getStatus().equals("1")){
				checkUseCoupons = false;
				break;
			}
			allRateRises =allRateRises.add(coupons.getRate_rises());
		}
		if(!checkUseCoupons){
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", "对不起，使用的加息券中存在已使用过的加息券，请重新选择！");
			return rtnMap;
		}
		
		if(!checkProductType){
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", "对不起，您选择的加息券不是全部为活期券或不是全部为定期券，请重新选择。");
			return rtnMap;
		}else{
			paramsMap.put("status", "1");
			paramsMap.put("productId",productId);
			paramsMap.put("useFlag", "1");
			//根据ID查询加息券列表
			List<RateRisesCoupons> useCouponsList = this.rateRisesCouponsDao.getRateRisesCouponsListByOrderId(paramsMap);
			//判断是定期还是活期
			
			//定期
			if(orderProductType.equals("108")){
				
				//判断定期订单是否已经使用加息券
				if(useCouponsList!=null && useCouponsList.size()>0){
					rtnMap.put("rescode", Consts.CHECK_CODE);
					rtnMap.put("resmsg", "");
					rtnMap.put("resmsg_cn", "对不起，该订单已经使用过加息券，请选择其他定期订单。");
					return rtnMap;
				}else{
					
					//判断定期是否使用多张加息券
					if(rateIdsArray.length>1){
						rtnMap.put("rescode", Consts.CHECK_CODE);
						rtnMap.put("resmsg", "");
						rtnMap.put("resmsg_cn", "定期订单只能使用一张加息券，请重新选择！");
						return rtnMap;
					}else{
						/*//判断加息券的使用期数
						Integer loanPeriods = jsonObject.getInt("LOAN_PERIODS");
						RateRisesCoupons useCoupons = couponsList.get(0);
						if(useCoupons.getRate_rises_days()!=loanPeriods){
							rtnMap.put("rescode", Consts.CHECK_CODE);
							rtnMap.put("resmsg", "");
							rtnMap.put("resmsg_cn", "加息的期数和订单的借款期数不相同，请重新选择！");
							return rtnMap;
						}else{
							//使用加息券
							
						}*/
						String scatteredId = jsonObject.getString("SCATTERED_LOAN_ID");
						this.useRateRisesCouponsActive(Long.parseLong(orderId), couponsList,"1",scatteredId);
						
					}
				}
			}
			else if(orderProductType.equals("109")){
				BigDecimal maxRateRises = new BigDecimal(findParamValueByName("sssq_max_rate_rises"));
				//加息总利率不能超过最大利率
				//已使用的加息券总利率
				BigDecimal useRateRises = BigDecimal.ZERO;
				for(RateRisesCoupons useCoupon:useCouponsList){
					useRateRises = useRateRises.add(useCoupon.getRate_rises());
				}
				allRateRises = allRateRises.add(useRateRises);
				if(allRateRises.compareTo(maxRateRises)>0){
					rtnMap.put("rescode", Consts.CHECK_CODE);
					rtnMap.put("resmsg", "");
					rtnMap.put("resmsg_cn", "当日使用的加息券总利率大于"+maxRateRises.doubleValue()+"%，请重新选择加息券！");
					return rtnMap;
				}else{
					//使用加息券
					this.useRateRisesCouponsActive(Long.parseLong(orderId), couponsList,"1",null);
				}
				
			}
		}
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "使用加息券成功");
		return rtnMap;
	}
	
	/**
	 * 用户抽奖加息券方法
	 * @param paramsMap
	 * @return
	 * @throws Exception 
	 * @throws NumberFormatException 
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public Map<String, Object> userCouponsLuckDraw(Map<String, Object> paramsMap) throws NumberFormatException, Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		//Long userId = Long.parseLong(paramsMap.get("userId").toString());
		
		CouponsLuckDraw couponsLuckDraw = couponsLuckDrawDao.queryCouponsLuckDrawByUserId(paramsMap);
		
		//判断是否存在抽奖次数
		if(couponsLuckDraw!=null){
			//判断是否还能继续抽奖
			Integer restDrawCount = couponsLuckDraw.getDraw_rest_count();
			
			if(restDrawCount>0){
				//抽取加息券 更新抽奖表
				int resultCont =  this.couponsLuckDrawDao.updateCouponsDrawLuckInfo(couponsLuckDraw);
				
				if(resultCont>0){
					
					paramsMap.put("type", 5);
					rtnMap = addRateRisesCoupons(paramsMap);
					String rescode = rtnMap.get("rescode").toString();
					
					if(rescode.equals(Consts.SUCCESS_CODE)){
						//更新抽奖表信息
						rtnMap.put("rescode", Consts.SUCCESS_CODE);
						rtnMap.put("resmsg_cn", "用户抽奖成功");
					}else{
						rtnMap.put("rescode", Consts.ERROR_CODE);
						rtnMap.put("resmsg", "");
						rtnMap.put("resmsg_cn", "对不起，抽奖出错！");
					}
				}else{
					rtnMap.put("rescode", Consts.CHECK_CODE);
					rtnMap.put("resmsg", "");
					rtnMap.put("resmsg_cn", "对不起，抽奖次数不足！");
				}
				
				
			}else{
				rtnMap.put("rescode", Consts.CHECK_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("resmsg_cn", "对不起，抽奖次数不足！");
			}
		}else{
			rtnMap.put("rescode", Consts.CHECK_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", "对不起，您现在还没有抽奖的机会，请投资之后再进行抽奖！");
		}
		return rtnMap;
	}
	
	/**
	 * 查询用户抽奖表信息
	 */
	@Override
	public Map<String, Object> showCouponsLuckDraw(Map<String, Object> paramsMap) {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		CouponsLuckDraw couponsLuckDraw = couponsLuckDrawDao.queryCouponsLuckDrawByUserId(paramsMap);
		
		if(couponsLuckDraw!=null){
			rtnMap.put("drawRestCount", couponsLuckDraw.getDraw_rest_count());
			rtnMap.put("couponsLuckDraw", couponsLuckDraw);
			rtnMap.put("rescode", Consts.SUCCESS_CODE);
			rtnMap.put("resmsg_cn", "查询成功！");
		}else{
			rtnMap.put("rescode", Consts.SUCCESS_CODE);
			rtnMap.put("drawRestCount", 0);
			rtnMap.put("couponsLuckDraw", couponsLuckDraw);
			rtnMap.put("resmsg_cn", "对不起，您现在还没有抽奖的机会，请投资之后再进行抽奖！");
		}
		return rtnMap;
	}
	
	/**
	 * 根据分享人手机号查询抢券人信息
	 */
	@Override
	public Map<String, Object> queryLootShareInfo(Map<String, Object> paramsMap) {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		List<LootShare> lootShareList =  this.rateRisesCouponsDao.queryLootShareInfoByShareMobile(paramsMap);
		rtnMap.put("lootShareList", lootShareList);
		rtnMap.put("lootShareListSize", lootShareList.size());
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功！");
		return rtnMap;
	}
	
	/**
	 * 根据加息券ID的借款期数查询上架表
	 */
	@Override
	public Map<String, Object> queryScatteredByRateId(
			Map<String, Object> paramsMap) {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(paramsMap.get("loanId")==null){
			String rateId = paramsMap.get("rateId").toString();
			String [] rateIdsArray = new String [] {rateId};
			
			List<RateRisesCoupons> couponsList = this.rateRisesCouponsDao.getRateRisesListByRateIds(rateIdsArray);
			
			RateRisesCoupons coupons = couponsList.get(0);
			
			Integer rateRisesDays = coupons.getRate_rises_days();
			if(coupons.getRemanDays()==0){
				paramsMap.put("rateRisesDays", rateRisesDays);
			}else{
				paramsMap.put("remanDays", coupons.getRemanDays());
			}
			
			List<Scattered> loanList = this.loanDao.queryScatteredByRateId(paramsMap);
			if(loanList.size()>0){
				Scattered sc = loanList.get(0);
				
				Map<String,Object> scMap = new HashMap<String,Object>();
				// id
				scMap.put("scatteredLoanId", sc.getId());
				// 产品名称
				scMap.put("productName", sc.getProductName());
				// 借款用途
				scMap.put("borrowType", sc.getBorrowType());
				// 年利率
				scMap.put("annualRate", sc.getAnnualRate());
				// 剩余期数
				scMap.put("remanPeriods", sc.getRemanPeriods());
				//剩余天数
				scMap.put("remanDays", sc.getRemanDays());
				// 显示名字
				if ("1".equals(sc.getSellingType())) {
					if(coupons.getRemanDays()==0){
						scMap.put("showName", "铃铛宝定期(" + sc.getRemanPeriods() + "个月)");
					}else{
						scMap.put("showName", "铃铛宝定期(" + sc.getRemanDays() + "天)");
					}
				} else {
					scMap.put("showName", "铃铛宝活期");
				}
				// 借款总额
				scMap.put("contactAmount", sc.getContactAmount());
				// 上架金额
				scMap.put("saleTotalAmount", sc.getSaleTotalAmount());
				// 起投金额
				scMap.put("investMinAmount", sc.getInvestMinAmount());
				// 投资进度%
				scMap.put("finishedRatio",
						DecimalFormatUtil.getDecimalFormat0(BigDecimal.ONE.compareTo(sc.getFinishedRatio()) > 0
								&& BigDecimal.ZERO.compareTo(sc.getFinishedRatio()) < 0 ? BigDecimal.ONE : sc.getFinishedRatio()));
				// 剩余金额
				scMap.put("remanAmount", sc.getRemanAmount());
				// 每份金额
				scMap.put("perServingAmount", sc.getPerServingAmount());
				// 可否购买(Y/N)
				scMap.put("openSelling", sc.getOpenSelling());
				// 标的ID
				scMap.put("loanId", sc.getBidId());
				// 理财计划ID
				scMap.put("planId", sc.getPlanId());
				// 下架时间
				scMap.put("endSaleTime", sc.getEndSaleTime()==null?"":sdf.format(sc.getEndSaleTime()));
				// 上架时间
				scMap.put("startSellingTime", sc.getStartSellingTime()==null?"":sdf.format(sc.getStartSellingTime()));

				// 是否推荐 1：推荐 0 不推荐
				scMap.put("isRecommend", sc.getIsRecommend());
				// 上架类别：1-散标，2-随存随取
				scMap.put("sellingType", sc.getSellingType());
				
				if ("2".equals(sc.getSellingType())) {
					DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	
					int day = 0;
					int hour = 0;
					int min = 0;
					int sec = 0;
					try {
						Date dateTime=sc.getStartSellingTime();   //产品上架时间
						logger.info("[上架时间]====>"+df.format(dateTime));
						logger.info("[当前时间]====>"+df.format(new Date(System.currentTimeMillis())));
						long time1 = System.currentTimeMillis();  //当前时间
						long time2 = dateTime.getTime();          //上架时间
						logger.info("[当前time1]-->"+time1);
						logger.info("[上架time2]-->"+time2);
						long diff = time2 - time1;
						if (diff >= 0) {
							day = (int) (diff / (24 * 60 * 60 * 1000));
							hour = (int) (diff / (60 * 60 * 1000) - day * 24);
							min = (int) ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
							sec = (int) (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);	
						} else {
							day=0;  hour=0;  min=0; sec=0;
						}
					logger.info("[上架时间距离当前时间]-->" + day + "天" + hour + "小时" + min + "分" + sec + "秒");
					} catch (Exception e) {
						e.printStackTrace();
						logger.info("[获取时间发生异常]-->" + e.getMessage());
					}
					scMap.put("day", day);
					scMap.put("hour", hour);
					scMap.put("min", min);
					scMap.put("sec", sec);
				}
				for (String key : scMap.keySet()) {
					rtnMap.put(key, scMap.get(key));
				}
				rtnMap.put("scattered", sc);
				rtnMap.put("rescode", Consts.SUCCESS_CODE);
				rtnMap.put("resmsg_cn", "查询成功！");
			}else{
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
				rtnMap.put("resmsg_cn", "对不起，现在还没有符合该加息券的产品！");
			}
		}else{
			Scattered sc = this.loanDao.queryScatteredByLoanId(paramsMap);
			if(sc!=null){
				Map<String,Object> scMap = new HashMap<String,Object>();
				// id
				scMap.put("scatteredLoanId", sc.getId());
				// 产品名称
				scMap.put("productName", sc.getProductName());
				// 借款用途
				scMap.put("borrowType", sc.getBorrowType());
				// 年利率
				scMap.put("annualRate", sc.getAnnualRate());
				// 剩余期数
				scMap.put("remanPeriods", sc.getRemanPeriods());
				// 显示名字
				if ("1".equals(sc.getSellingType())) {
					scMap.put("showName", "铃铛宝定期(" + sc.getRemanPeriods() + "个月)");
				} else {
					scMap.put("showName", "铃铛宝活期");
				}
				// 借款总额
				scMap.put("contactAmount", sc.getContactAmount());
				// 上架金额
				scMap.put("saleTotalAmount", sc.getSaleTotalAmount());
				// 起投金额
				scMap.put("investMinAmount", sc.getInvestMinAmount());
				// 投资进度%
				scMap.put("finishedRatio",
						DecimalFormatUtil.getDecimalFormat0(BigDecimal.ONE.compareTo(sc.getFinishedRatio()) > 0
								&& BigDecimal.ZERO.compareTo(sc.getFinishedRatio()) < 0 ? BigDecimal.ONE : sc.getFinishedRatio()));
				// 剩余金额
				scMap.put("remanAmount", sc.getRemanAmount());
				// 每份金额
				scMap.put("perServingAmount", sc.getPerServingAmount());
				// 可否购买(Y/N)
				scMap.put("openSelling", sc.getOpenSelling());
				// 标的ID
				scMap.put("loanId", sc.getBidId());
				// 理财计划ID
				scMap.put("planId", sc.getPlanId());
				// 下架时间
				scMap.put("endSaleTime", sc.getEndSaleTime()==null?"":sdf.format(sc.getEndSaleTime()));
				// 上架时间
				scMap.put("startSellingTime", sc.getStartSellingTime()==null?"":sdf.format(sc.getStartSellingTime()));

				// 是否推荐 1：推荐 0 不推荐
				scMap.put("isRecommend", sc.getIsRecommend());
				// 上架类别：1-散标，2-随存随取
				scMap.put("sellingType", sc.getSellingType());
				
				if ("2".equals(sc.getSellingType())) {
					DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	
					int day = 0;
					int hour = 0;
					int min = 0;
					int sec = 0;
					try {
						Date dateTime=sc.getStartSellingTime();   //产品上架时间
						logger.info("[上架时间]====>"+df.format(dateTime));
						logger.info("[当前时间]====>"+df.format(new Date(System.currentTimeMillis())));
						long time1 = System.currentTimeMillis();  //当前时间
						long time2 = dateTime.getTime();          //上架时间
						logger.info("[当前time1]-->"+time1);
						logger.info("[上架time2]-->"+time2);
						long diff = time2 - time1;
						if (diff >= 0) {
							day = (int) (diff / (24 * 60 * 60 * 1000));
							hour = (int) (diff / (60 * 60 * 1000) - day * 24);
							min = (int) ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
							sec = (int) (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);	
						} else {
							day=0;  hour=0;  min=0; sec=0;
						}
					logger.info("[上架时间距离当前时间]-->" + day + "天" + hour + "小时" + min + "分" + sec + "秒");
					} catch (Exception e) {
						e.printStackTrace();
						logger.info("[获取时间发生异常]-->" + e.getMessage());
					}
					scMap.put("day", day);
					scMap.put("hour", hour);
					scMap.put("min", min);
					scMap.put("sec", sec);
				}
				for (String key : scMap.keySet()) {
					rtnMap.put(key, scMap.get(key));
				}
				rtnMap.put("scattered", sc);
				rtnMap.put("rescode", Consts.SUCCESS_CODE);
				rtnMap.put("resmsg_cn", "查询成功！");
			}else{
				rtnMap.put("rescode", Consts.ERROR_CODE);
				rtnMap.put("resmsg", "");
			}
		}
		return rtnMap;
	}
	/**
	 * 拼接基础参数
	 * @param userId
	 * @param mobile
	 * @param coupons
	 * @return
	 * @throws ParseException 
	 */
	private RateRisesCoupons getBaseInfo(String userId,String mobile,Date currentDate) throws ParseException{
		
		RateRisesCoupons coupons = new RateRisesCoupons();
		coupons.setStatus("0");
		coupons.setCreate_time(currentDate);
		coupons.setUser_id(StringUtils.isBlank(userId)?null:Long.parseLong(userId));
		coupons.setMobile(mobile);
		return coupons;
	}
	
	@Override
	public String findParamValueByName(String key) throws Exception {
		List<String> listStr = new ArrayList<String>();
		listStr.add(key);
		//去BL查询系统参数表
		List<Map<String, Object>> extractFeeRate = this.rateRisesCouponsDao.queryParamName(listStr);
		if (extractFeeRate !=null && extractFeeRate.size() > 0) {
			return (String) extractFeeRate.get(0).get("VALUE");
		}
		return null;
	}
	
	//格式化时间参数
	private List<RateRisesCoupons> formatDateParams(List<RateRisesCoupons> rateRisesCouponsList){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String periodShowName=loanDao.queryBitShowNamePeriod();
		String currentShowName=loanDao.queryBitShowNameCurrent();
		
		for(RateRisesCoupons coupons:rateRisesCouponsList){
			//格式化时间
			if(coupons.getValidity_period()!=null){
				coupons.setValidity_period_str(sdf.format(coupons.getValidity_period()));
			}
			if(coupons.getBegin_date()!=null){
				coupons.setBegin_date_str(sdf.format(coupons.getBegin_date()));
			}
			if(coupons.getEnd_date()!=null){
				coupons.setBegin_date_str(sdf.format(coupons.getEnd_date()));
			}
			if(coupons.getCreate_time()!=null){
				coupons.setCreate_time_str(sdf.format(coupons.getCreate_time()));
			}
			if(coupons.getUpdate_time()!=null){
				coupons.setUpdate_time_str(sdf.format(coupons.getUpdate_time()));
			}
			//格式化产品名称
			if(coupons.getProduct_id().equals("108")){
				if(null ==coupons.getRemanDays() || coupons.getRemanDays()==0){
					coupons.setProduct_id_str(periodShowName+coupons.getRate_rises_days()+"月期");
				}else{
					coupons.setProduct_id_str(periodShowName+coupons.getRemanDays()+"天");
				}				
			}else if(coupons.getProduct_id().equals("109")){
				coupons.setProduct_id_str(currentShowName);
			}
		}
		return rateRisesCouponsList;
	}
	
	//使用加息券-主动使用
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public void useRateRisesCouponsActive(Long orderId,List<RateRisesCoupons> couponsList,String useFlag,String scatteredId) throws Exception{
		Map<String, Object> map = new HashMap<String,Object>();
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		cal.setTime(new Date());
		for(RateRisesCoupons coupons : couponsList){
			coupons.setOrder_id(orderId);
			coupons.setStatus("1");
			coupons.setUpdate_time(new Date());
			//如果只有手机号，则根据手机号查询用户id进行填写
			if(coupons.getUser_id()==null){
				map.put("mobile", coupons.getMobile());
				User user = this.usersDao.getUserByParm(map);
				coupons.setUser_id(Long.parseLong(user.getId().toString()));
			}
			if(StringUtils.isBlank(coupons.getMobile())){
				User user = this.usersDao.getUserDetail(coupons.getUser_id().toString());
				coupons.setMobile(user.getMobile());
			}
			Integer rateRisesDays = coupons.getRate_rises_days();
			//根据scatteredId查询计息日
			Map<String,Object> scatteredMap = new HashMap<String,Object>();
			scatteredMap.put("loanId", scatteredId);
			if(coupons.getProduct_id().equals("108")){
				Integer valueDate = this.loanDao.queryScatteredLoanValueDateById(scatteredMap);
				cal.add(Calendar.DATE, valueDate);
			}
			//设置加息券的开始使用日期和结束使用日期
			coupons.setBegin_date(sdf.parse(sdf.format(cal.getTime())));
			if(coupons.getProduct_id().equals("109")){
				cal.add(Calendar.DATE, (rateRisesDays-1));
				coupons.setEnd_date(sdf.parse(sdf.format(cal.getTime())));
			}else if(coupons.getProduct_id().equals("108")){
				//如果remanDays为0，表示短期标还未启用，否则启用
				if(coupons.getRemanDays()==0){
					cal.add(Calendar.MONTH, rateRisesDays);
					coupons.setEnd_date(sdf.parse(sdf.format(cal.getTime())));
				}else{
					cal.add(Calendar.DATE, coupons.getRemanDays()-1);
					coupons.setEnd_date(sdf.parse(sdf.format(cal.getTime())));
				}
			}
			coupons.setUse_flag(useFlag);
			//更新加息券信息
			this.rateRisesCouponsDao.updateRateRisesCouponsInfo(coupons);
		}
	}
	
	//使用加息券-被动使用
	public void useRateRisesCouponsPassive(Long userId,String mobile,List<RateRisesCoupons> couponsList,String useFlag) throws Exception{
		Map<String, Object> map = new HashMap<String,Object>();
		//判断是否存在用户 如果存在用户则填充用户ID
		if(userId==null){
			map.put("mobile", mobile);
			User user = this.usersDao.getUserByParm(map);
			if(user!=null){
				userId = Long.parseLong(user.getId().toString());
			}
			
		}
		
		//判断是否可以使用加息券
		if(userId!=null){
			//根据用户ID查询用户在投活期订单
			String transCode = "E310064";
			Map<String, Object> queryCoreMap = new HashMap<String, Object>();
			queryCoreMap.put("userId", userId);
			queryCoreMap.put("planId", "109");
			String jsonStr = CommonUtil.constructJsonStr(transCode,
					null, queryCoreMap);
			String rtnStr = CommonUtil.getCoreValue(jsonStr);
			JSONObject jsonObject = JSONObject.fromObject(rtnStr);
			boolean existOrderId = Boolean.parseBoolean(jsonObject.getString("existOrderId"));
			//存在活期订单直接进行使用
			if(existOrderId){
				Long orderId = jsonObject.getLong("orderId");
				useRateRisesCouponsActive(orderId, couponsList, useFlag,null);
			}
		}
	}
	
	/**
	 * 查询加息券信息
	 */
	@Override
	public List<RateRisesCoupons> getRateRisesListByRateIds(
			String[] rateIdsArray) {
		return this.rateRisesCouponsDao.getRateRisesListByRateIds(rateIdsArray);
	}
	/**
	 * 根据UserId查询加息券信息
	 */
	@Override
	public List<RateRisesCoupons> getRateRisesCouponsListByOrderId(
			Map<String, Object> paramsMap) {
		return this.rateRisesCouponsDao.getRateRisesCouponsListByOrderId(paramsMap);
	}
	
	/**
	 * 查询加息券信息
	 */
	@Override
	public Map<String, Object> queryRateRisesByRateId(
			Map<String, Object> paramsMap) {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		
		String rateIds = paramsMap.get("rateIds").toString();
		String [] rateIdsArray = rateIds.split(",");
		
		
		List<RateRisesCoupons> couponsList = this.rateRisesCouponsDao.getRateRisesListByRateIds(rateIdsArray);
		
		RateRisesCoupons rateRisesCoupons = null;
		if(couponsList.size()>0){
			rateRisesCoupons = couponsList.get(0);
		}
		
		rtnMap.put("rateRisesCoupons", rateRisesCoupons);
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功！");
		
		
		return rtnMap;
	}
	/**
	 * 根据UserId查询用户当前在投活期订单ID
	 * @throws Exception 
	 */
	@Override
	public Long getUserLDActiveOrderId(String userId) throws Exception {
		String transCode = "E310064";
		Map<String, Object> queryCoreMap = new HashMap<String, Object>();
		queryCoreMap.put("userId", userId);
		queryCoreMap.put("planId", "109");
		String jsonStr = CommonUtil.constructJsonStr(transCode,
				null, queryCoreMap);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		boolean existOrderId = Boolean.parseBoolean(jsonObject.getString("existOrderId"));
		//存在活期订单直接进行使用
		if(existOrderId){
			Long orderId = jsonObject.getLong("orderId");
			return orderId;
		}
		return null;
	}
	
	/**
	 * 根据订单ID查询所有使用的加息券列表
	 * @param paramsMap
	 * @return
	 */
	@Override
	public List<RateRisesCoupons> getAllRateRisesCouponsListByOrderId(Map<String, Object> paramsMap) {
		return this.rateRisesCouponsDao.getAllRateRisesCouponsListByOrderId(paramsMap);
	}
	
	/**
	 * 查询用户当日活期加息利率
	 * @throws Exception 
	 */
	@Override
	public Map<String, Object> queryUserTodayRateRises(
			Map<String, Object> paramsMap) throws Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		String userId = paramsMap.get("userId").toString();
		Long orderId = getUserLDActiveOrderId(userId);
		String couponsRateRises = "";
		if(orderId==null){
			couponsRateRises = "0";
		}else{
			paramsMap.put("status", "1");
			paramsMap.put("productId","109");
			paramsMap.put("useFlag", "1");
			//根据ID查询加息券列表
			List<RateRisesCoupons> useCouponsList = this.rateRisesCouponsDao.getRateRisesCouponsListByOrderId(paramsMap);
			BigDecimal useRateRises = BigDecimal.ZERO;
			for(RateRisesCoupons useCoupon:useCouponsList){
				useRateRises = useRateRises.add(useCoupon.getRate_rises());
			}
			couponsRateRises = useRateRises.toString();
		}
		rtnMap.put("couponsRateRises", couponsRateRises);
		return rtnMap;
	}
	
	/**
	 * 获取用户当日加息信息
	 * 需要增加文案
	 */
	@Override
	public Map<String,Object> getTodayUserSignInfo(Map<String, Object> paramsMap) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		UserSign userSign = this.rateRisesCouponsDao.queryUserCurrentSign(paramsMap);
		String currentSign = "N";
		if(userSign!=null){
			currentSign = "Y";
			resultMap.put("signFlag", userSign.getSign_flag());
		}
		resultMap.put("currentSign", currentSign);
		//查询活动文案
		String activtyText = this.rateRisesCouponsDao.queryTextSettingByName("sign_text");
		
		resultMap.put("activtyText", activtyText);
		
		return resultMap;
	}
	
	/**
	 * 单独返回加息券列表相关
	 */
	@Override
	public List<RateRisesCoupons> queryRateRisesCouponsListByUser(
			Map<String, Object> paramsMap) throws Exception {
		//如果存在用户 则填充mobile或userId
		if(paramsMap.get("userId")==null){
			User user = this.usersDao.getUserByParm(paramsMap);
			if(user!=null){
				paramsMap.put("userId", user.getId());
			}
		}
		if(paramsMap.get("mobile")==null || StringUtils.isBlank(paramsMap.get("mobile").toString()) ){
			String userId = paramsMap.get("userId").toString();
			User user = this.usersDao.getUserDetail(userId);
			if(user!=null){
				paramsMap.put("mobile", user.getMobile());
			}
		}
		
		//判断product类型
		if(paramsMap.get("product")!=null){
			if(StringUtils.isNotBlank(paramsMap.get("product").toString())){
				Integer product = Integer.parseInt(paramsMap.get("product").toString());
				switch(product){
				case 0:
					paramsMap.put("productId", "109");
					break;
				case 1:
					paramsMap.put("productId", "108");
					paramsMap.put("rateRisesDays", 1);
					break;
				case 3:
					paramsMap.put("productId", "108");
					paramsMap.put("rateRisesDays", 3);
					break;
				case 6:
					paramsMap.put("productId", "108");
					paramsMap.put("rateRisesDays", 6);
					break;
				case 12:
					paramsMap.put("productId", "108");
					paramsMap.put("rateRisesDays", 12);
					break;
				case 999:
					paramsMap.put("productId", "108");
					break;
				default : 
					paramsMap.put("remanDays", product);
				}
			}
		}
		
		List<RateRisesCoupons> rateCouponsList = this.rateRisesCouponsDao.queryRateRisesCouponsListByParams(paramsMap);
		return rateCouponsList;
	}
	
	@Override
	public Integer queryRateRisesCouponsListByUserCount(
			Map<String, Object> paramsMap) throws Exception {
		//如果存在用户 则填充mobile或userId
		if(paramsMap.get("userId")==null){
			User user = this.usersDao.getUserByParm(paramsMap);
			if(user!=null){
				paramsMap.put("userId", user.getId());
			}
		}
		if(paramsMap.get("mobile")==null || StringUtils.isBlank(paramsMap.get("mobile").toString()) ){
			String userId = paramsMap.get("userId").toString();
			User user = this.usersDao.getUserDetail(userId);
			if(user!=null){
				paramsMap.put("mobile", user.getMobile());
			}
		}
		
		//判断product类型
		if(paramsMap.get("product")!=null){
			if(StringUtils.isNotBlank(paramsMap.get("product").toString())){
				Integer product = Integer.parseInt(paramsMap.get("product").toString());
				switch(product){
				case 0:
					paramsMap.put("productId", "109");
					break;
				case 1:
					paramsMap.put("productId", "108");
					paramsMap.put("rateRisesDays", 1);
					break;
				case 3:
					paramsMap.put("productId", "108");
					paramsMap.put("rateRisesDays", 3);
					break;
				case 6:
					paramsMap.put("productId", "108");
					paramsMap.put("rateRisesDays", 6);
					break;
				case 12:
					paramsMap.put("productId", "108");
					paramsMap.put("rateRisesDays", 12);
					break;
				case 999:
					paramsMap.put("productId", "108");
					break;
				default : 
					paramsMap.put("remanDays", product);
				}
			}
		}
		int totalNum = this.rateRisesCouponsDao.queryRateRisesCouponsListByParamsCount(paramsMap);
		return totalNum;
	}
	
	
	private String getSignDateStr(String signDateStr,char signFlag, Date currentDate){
		char[] signDateStrArray = signDateStr.toCharArray();
		 
		SimpleDateFormat sdfSign = new SimpleDateFormat("dd");
		String day = sdfSign.format(currentDate);
		int dayIndex = Integer.parseInt(day);
		 
		signDateStrArray[dayIndex-1] = signFlag;
		
		signDateStr = new String(signDateStrArray);
		return signDateStr;
	}
}
